const App = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    options: {},
    code:'',
    detail:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let _this = this,scene = decodeURIComponent(options.scene)
    console.log(scene.split('=')[1])
    console.log(wx.getStorageSync('ACCESS_TOKEN'))
    if(wx.getStorageSync('ACCESS_TOKEN')){
      _this.setData({code: scene.split('=')[1]})
      _this.getDetail()
    }else{
      App.args.page.onLoad(_this, options)
    }
  },
  errModel(msg) {
    wx.showModal({
      title: '提示',
      content: msg,
      showCancel: false,
      success (res) {
        if (res.confirm) {
          App.navigationTo('pages/index/index') 
          wx.exitMiniProgram()
        }
      }
    })
  },
  getDetail() {
    let _this = this
    wx.showLoading({title: '加载中',mask:true})
    App.args.request({
      url:App.args.api.siteinfo.sitelive+'activity/couponqrcode',
      data:{
        storeId:App.args.api.siteinfo.acid,
        couponId:_this.data.code
      },
      success(e){
        wx.hideLoading()
        if(e.result !== 0) {
          _this.errModel('系统错误，请重新扫码或联系管理员')
        }else{
          if(e.data[0].is_use == 1) {
            _this.errModel('此券以核销')
            return false
          }
          _this.setData({detail: e.data[0]})
          wx.showModal({
            title: '提示',
            content: '是否核销此优惠券',
            success (res) {
              if (res.confirm) {
                _this.onSubmitExtract()
              } else if (res.cancel) {
                App.navigationTo('pages/index/index') 
                wx.exitMiniProgram()
              }
            }
          })
        }
      }
    });
  },
  /**
   * 确认核销
   */
  onSubmitExtract() {
    let _this = this
    wx.showLoading({title: '加载中',mask:true})
    wx.request({
      url:App.args.api.siteinfo.sitelive+'activity/hexiao',
      data:{
        couponId:_this.data.code,
        hosId:App.args.api.siteinfo.acid,
        clerk_open_id:wx.getStorageSync('ACCESS_TOKEN')
      },
      success(e){
        wx.hideLoading()
        e.statusCode !== 200 ? _this.errModel('系统错误') : e.data.result < 0 ? _this.errModel(e.data.message) : _this.errModel('核销成功')
      }
    })
  },
})